package com.demo.viewpager;

import android.graphics.drawable.Drawable;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

public class VPMainActivity extends AppCompatActivity {

    private ViewPager ma_vp;
    private ImageView vp_img;
    private ViewGroup group;
    private ImageView[] imageViews;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vpactivity_main);
        ma_vp = (ViewPager) findViewById(R.id.ma_vp);
        group = (ViewGroup) findViewById(R.id.layout_dot);

        final ArrayList<Drawable> list_img = new ArrayList<>();
        list_img.add(getResources().getDrawable(R.drawable.pic1));
        list_img.add(getResources().getDrawable(R.drawable.pic2));
        list_img.add(getResources().getDrawable(R.drawable.pic3));

        /**
         * 有几张图片下面就显示几个小圆点
         */
        imageViews = new ImageView[list_img.size()];
        LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);//每个圆点大小
        // 设置每个小圆点距离左边的间距
        margin.setMargins(15, 0, 0, 0);

        for (int i = 0; i < list_img.size(); i++) {

            imageView = new ImageView(VPMainActivity.this);

            // 设置每个小圆点的宽高
            imageView.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
            imageViews[i] = imageView;

            if (i == 0) {
                // 默认选中第一张图片
                imageViews[i].setBackgroundResource(R.drawable.img_black);
            } else {
                // 其他图片都设置未选中状态
                imageViews[i].setBackgroundResource(R.drawable.img_white);
            }
            group.addView(imageViews[i], margin);
        }


        ViewPagerAdater adater = new ViewPagerAdater(VPMainActivity.this, list_img);
        ma_vp.setAdapter(adater);
        ma_vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {


                //for-each循环将所有的imageViews设置为img_white
                for (ImageView imageView : imageViews) {
                    imageView.setImageResource(R.drawable.img_white);
                }
                //设置当前显示的页面的dot设置为dot_focused
                imageViews[i % 3].setImageResource(R.drawable.img_black);
            }

            @Override
            public void onPageScrollStateChanged(int i) {


            }
        });

    }
}
